--华容突围
local Msg = require("core.Msg")
local Map = require("core.Map")
local TD2Excel = require("excel.TD2").base
local MonsterExcel = require("excel.Monster").monster
local ObjMonster = require("core.ObjMonster")
local Obj = require("core.Obj")
local CopyL = require("copy.CopyL")
local CopyDefine = require("copy.Define")
local Lang = require("common.Lang")

local function getMonsterInfo(sceneID, monsterID)
  local monster
  for _, v in pairs(Obj.scenes[sceneID]) do
       if v.monster_id == monsterID then
            monster = v
            break
       end       
  end
  if monster then
      return ObjMonster.getHp(monster), ObjMonster.getHpMax(monster)
  end
  local cf = MonsterExcel[monsterID]
  local hp = cf.hp_max * cf.hp_init_p / 100
  return 0,hp
end

local function sendTDInfo(scene_id, human)
  local scene_id = scene_id or human.scene_id
  local mapid = Map.scene_id_to_map_id[scene_id]
  if not mapid or not TD2Excel[mapid] then
      return
  end
  local conf = TD2Excel[mapid] 
  local msg = Msg.gc.GC_COPY_TD2_INFO
  msg.selfHP,msg.selfMaxHP = getMonsterInfo(scene_id, conf.selfMonsterID)
  msg.bossHP,msg.bossMaxHP = getMonsterInfo(scene_id, conf.targetMonsterID)
  
  local rect = Map.getRects(mapid, conf.selfAreaID)
  msg.selfX = (rect[1][1] + rect[1][3])/2
  rect = Map.getRects(mapid, conf.targetAreaID)
  msg.bossX = (rect[1][1] + rect[1][3])/2
  
  if human then
    Msg.send(msg, human.fd)
  else
    Obj.sendScene(msg, scene_id)
  end
end

function onTDTimer(copyID, roomID)
  -- 定时刷新info 
  local mapList = CopyL.copyList[copyID][roomID]
    for mapID,sceneID in pairs(mapList) do
        if Obj.scenes[sceneID] then
           sendTDInfo(sceneID)
        end
    end
end


function onTDHumanEnterCopyScene(human)
  sendTDInfo(nil, human)
end

function onMonsterBeHit(attacker, monster, monsterID, shanghai, copyID, roomID, sceneID)
  for mapid, data in pairs(TD2Excel) do
      if data.selfMonsterID == monsterID or data.targetMonsterID == monsterID then
          sendTDInfo(sceneID)
          break
      end
  end
end


function onMonsterDie(killer, monster, monsterID, copyID, roomID)
  for mapid, data in pairs(TD2Excel) do
      if data.selfMonsterID == monsterID then
          sendTDInfo(monster.scene_id)
          CopyL.roomFinish(copyID, roomID, CopyDefine.COPY_FINISH_TD_FAIL, Lang.COPY_FINISH_TD2_FAIL)
      end
  end
end